package RLK_JNDI;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import java.util.Hashtable;

import static javax.naming.Context.INITIAL_CONTEXT_FACTORY;
import static javax.naming.Context.SECURITY_AUTHENTICATION;

public class Example_02 {
    public NamingEnumeration<SearchResult> search(final String providerURL,
                                                  final String name,
                                                  final String filter,
                                                  final SearchControls cons) {
        try {
            Hashtable environment = new Hashtable();
            environment.put(INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
            environment.put(Context.PROVIDER_URL, providerURL);
            environment.put(SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);

            InitialLdapContext context = new InitialLdapContext(environment, null); // Resource allocated

            try {
                NamingEnumeration<SearchResult> result = context.search(name, filter, cons);
                return result;
            } finally {
                context.close(); // Resource released
            }
        } catch (NamingException e) {
            System.err.println("LDAP search failed: " + e.getMessage());
        }

        return null;
    }
}
